<?php

// +----------------------------------------------------------------------
// |ZBPHP[基于ThinkPHP5.1开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2019 http://www.benbenwangluo.com
// +----------------------------------------------------------------------
// | Author 似水星辰 [ 2630481389@qq.com ]
// +----------------------------------------------------------------------
// | 中犇软件 技术六部 出品
// +----------------------------------------------------------------------

namespace app\api\controller\v1;

use app\api\controller\Base;
use service\ApiReturn;
use app\user\model\Collection as CollectionModel;


/**
 * 收藏和足迹
 * Class Collection
 */
class Collection extends Base
{

   
    /**
     * 获取我的收藏
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @edit 晓风<215628355@qq.com> 2021年11月6日14:01:51
     * @created 2019/9/9 10:38
     */
    public function get_collection_list($data = [], $user = [])
    {
        $keywords = isset($data['keywords']) ? $data['keywords'] : '';     
        $rows = $data["list_rows"] ?? 8 ;
        switch($data["type"]){
            //商品收藏和足迹
            case 1:
            case 3:                
                return $this->getGoodList($user["id"], $data['type'], $keywords,$rows);    
            case 2:
               return $this->getArticleList($user["id"], $data['type'], $keywords,$rows);        
        }    
        return ApiReturn::r(0, [], lang('暂无数据'));      
    }
    
        /**
     * 添加/取消收藏（本接口适用于商品详情页，文章内容页等场景）
     * @param array $data
     * @param array $user
     * @author 似水星辰 [ 2630481389@qq.com ]
     * @created 2019/9/24 18:55
     */
    public function set_collection($data = [], $user = [])
    {
        $collect = new \app\user\model\Collection();
        $res = $collect->isCollection($user['id'], $data['type'], $data['collect_id']);
        if ($res) {
            // 取消收藏
           $collect->delCollection($user['id'], $data['type'], $data['collect_id']);          
           return ApiReturn::r(1, ['is_collection' => 0], "已取消");            
        } 
        switch($data['type'])
        {
            case 1://商品
            case 3:
                $msg = $data['type'] == 1 ? '收藏成功' : "已保存足迹";              
                $result = \app\goods\model\Goods::where("id",$data["collect_id"])->field("id")->find();
            break;
            case 2: //文章
                $msg = '收藏成功';             
                $result = \app\operation\model\Article::where("id",$data["collect_id"])->field("id")->find();
                break;
            default :
                return ApiReturn::r(0, [], "暂不支持该类型");      
        }
        if(!$result){
            return ApiReturn::r(0, [], "数据异常");      
        }
        $data['user_id'] = $user['id'];    
        $ret = $collect->create($data);        
        if ($ret) {
            return ApiReturn::r(1, ['is_collection' => 1], $msg);
        }
        return ApiReturn::r(0, [], '操作失败');
    }


    /**
     * 取消收藏（适用于个人中心-我的收藏-取消收藏）
     * @param array $data
     * @param array $user
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     * @created 2019/9/24 21:44
     */
    public function cancel_collection($data = [], $user = [])
    {
        $collect = new CollectionModel();
        $aid_str = $data['aid'] ?? 0;
        $aid_arr = explode(',', $aid_str);
        $res = $collect->where('aid', 'in', $aid_arr)
                ->where('type',$data['type'])
                ->where('user_id', $user['id'])
                ->delete();
        if ($res) {
            return ApiReturn::r(1, ['is_collection' => 0], '取消收藏成功');
        }
        return ApiReturn::r(0, [], '操作失败');       
    }

    
   
     /**
     * 获得商品收藏/足迹
     * @author 晓风
     */
    private function getGoodList($user_id,$type,$keywords = null,$size = 10 )
    {
        if(!in_array($type,[1,3])){
            return ApiReturn::r(1, [], '暂无数据');
        }
        $whereStr[] = ["user_collection.user_id","=",$user_id];
        $whereStr[] = ["user_collection.type","=", $type];
        if($keywords){
            $whereStr[] = ["goods.name","like",'%'.$keywords.'%'];
        }     
        //删除无效的收藏,仅删除没有的商品和后台标记删除的，下架和禁用的不删除
        CollectionModel::where("type","in",[1,3])->where("collect_id","not in",function($query){
            $query->name("goods")->where("is_delete",0)->field("id");
        })->delete();
        
        // 查询收藏的商品列表
        $list = CollectionModel::view('user_collection',"aid,user_id,collect_id,type,create_time,sku_id")//必传值
            ->view(
                "goods",
                "name as collect_title,thumb as collect_img,shop_price as collect_price,sales_sum as collect_sales,market_price,shop_price,sales_sum",
                "user_collection.collect_id = goods.id  and goods.is_delete = 0 and goods.is_sale =1 and goods.status = 1" //排除下架，禁用和删除
            )        
            ->where($whereStr)
            ->paginate($size);   
        $info = [];
        foreach ($list->items() as $item) {        
            $item["collect_num"] =   CollectionModel::where("type",$item["type"])->where("collect_id",$item["collect_id"])->count();            
            $item['collect_img'] = get_thumb($item['collect_img']);      
            $info[] = $item;
        }
        return ApiReturn::r(1, $this->getThinkPage($list,$info), '请求成功');
    }
    
    /**
     * 获得文章收藏
     * @author 晓风
     */
    private function getArticleList($user_id,$type,$keywords = null,$size = 10 )
    {
        if(!in_array($type,[2])){
            return ApiReturn::r(1, [], '暂无数据');
        }
        $whereStr[] = ["user_collection.user_id","=",$user_id];
        $whereStr[] = ["user_collection.type","=", $type];
        if($keywords){
            $whereStr[] = ["operation_article.title","like",'%'.$keywords.'%'];
        }     
        //删除无效的收藏
        CollectionModel::where("type",2)->where("collect_id","not in",function($query){
            $query->name("operation_article")->where("trash",0)->field("id");
        })->delete();
        
        // 查询收藏的商品列表
        $list = CollectionModel::view('user_collection',"aid,user_id,collect_id,type,create_time")//必传值
            ->view(
                "operation_article",
                "title as collect_title,img_url as collect_img",
                "user_collection.collect_id = operation_article.id  and operation_article.trash = 0 and operation_article.status = 1" //排除禁用和删除
            )        
            ->where($whereStr)
            ->paginate($size);   
        $info = [];
        foreach ($list->items() as $item) {        
            $item["article_comment_num"] =  Db::name('operation_article_comment')->where('article_id', '=', $item['collect_id'])->count();
            $item['collect_img'] = get_thumb($item['collect_img']);      
            $info[] = $item;
        }       
        return ApiReturn::r(1, $this->getThinkPage($list,$info), '请求成功');
    }

    
    /**
     * 我的商品足迹-按照时间分组
     * @author 晓风<215628355@qq.com>
     */
    public function foot_print($data = [], $user = [])
    {
        $type = $data['type'] ?? 1;
        $time = $data['time'] ?? date("Y-m-d", time());
        $start_time = $data['start_time'] ?? date("Y-m-d", time());
        $end_time = $data['end_time'] ?? date("Y-m-d", time());
        $keywords = $data['keywords'] ?? '';
        $list = [];       
        $whereStr = [
            ['user_collection.type', '=', 3],
            ['user_collection.user_id', '=', $user['id']],
            ['user_collection.status', '=', 1],
        ];
        // 查询收藏的商品列表        
        if ($type == 1) {
            //足迹管理1
            $whereStr[] = ['user_collection.collect_title', 'like', '%' . $keywords . '%'];
        } elseif ($type == 2) {
            //足迹管理2
            $whereStr[] = ['user_collection.create_time', '>=', strtotime($time)];
            $whereStr[] = ['user_collection.create_time', '<=', strtotime($time) + 24 * 3600];      
        } else {
            //足迹管理3
            $whereStr[] = ['user_collection.create_time', '>=', strtotime($start_time)];
            $whereStr[] = ['user_collection.create_time', '<=', strtotime($end_time) + 24 * 3600];
        }
       $collect = CollectionModel::view('user_collection',"aid,user_id,collect_id,type,create_time,sku_id")//必传值
            ->view(
                "goods",
                "name as collect_title,thumb as collect_img,shop_price as collect_price,sales_sum as collect_sales,market_price,shop_price,sales_sum",
                "user_collection.collect_id = goods.id  and goods.is_delete = 0 and goods.is_sale =1 and goods.status = 1" //排除下架，禁用和删除
            )        
            ->where($whereStr)
            ->order("user_collection.update_time desc")
            //->limit(100)
            ->select();   
        foreach ($collect as $item) {                      
            $item['collect_img'] = get_thumb($item['collect_img']);      
            $list[date("Y-m-d", strtotime($item['create_time']))][] = $item;
        }
        return ApiReturn::r(1, $list, 'ok');
    }
}
